<!--  工具栏 -->
<script setup lang="ts">
import { ref, watch } from 'vue';
import TableColumnSetting from '../../table-column-setting.vue';

interface Props {
  columns: AntDesign.TableColumn<any>[];
}

const props = defineProps<Props>();

interface Emits {
  (e: 'columns-change', columns: AntDesign.TableColumn<any>[]): void;
}

const emit = defineEmits<Emits>();

// 初始化列检查状态
function getColumnChecks(cols: AntDesign.TableColumn<any>[]): AntDesign.TableColumnCheck[] {
  const checks: AntDesign.TableColumnCheck[] = [];

  cols.forEach(column => {
    if (column.key) {
      checks.push({
        key: column.key as string,
        title: column.title as string,
        checked: true
      });
    }
  });

  return checks;
}

// 根据检查状态过滤列
function getColumns(
  cols: AntDesign.TableColumn<any>[],
  checks: AntDesign.TableColumnCheck[]
): AntDesign.TableColumn<any>[] {
  const columnMap = new Map<string, AntDesign.TableColumn<any>>();

  cols.forEach(column => {
    if (column.key) {
      columnMap.set(column.key as string, column);
    }
  });

  const filteredColumns = checks
    .filter(item => item.checked)
    .map(check => columnMap.get(check.key) as AntDesign.TableColumn<any>)
    .filter(Boolean);

  return filteredColumns;
}

// 列检查状态
const columnsState = ref<AntDesign.TableColumnCheck[]>(getColumnChecks(props.columns));

// 监听列检查状态变化，发出过滤后的列
watch(
  columnsState,
  newChecks => {
    const filteredColumns = getColumns(props.columns, newChecks);
    emit('columns-change', filteredColumns);
  },
  { deep: true }
);

// 监听 props.columns 变化，更新列检查状态
watch(
  () => props.columns,
  newColumns => {
    // 保持现有的检查状态，只更新新增的列
    const checkMap = new Map(columnsState.value.map(col => [col.key, col.checked]));
    const defaultChecks = getColumnChecks(newColumns);

    columnsState.value = defaultChecks.map(col => ({
      ...col,
      checked: checkMap.get(col.key) ?? col.checked
    }));
  },
  { deep: true }
);
</script>

<template>
  <div class="my12px flex-y-center justify-between">
    <!-- 左边自定义按钮 -->
    <ASpace>
      <slot name="customTooBtn"></slot>
    </ASpace>
    <!-- 右边固定按钮 -->
    <ASpace>
      <AButton type="primary" size="small">
        <template #icon>
          <icon-ant-design-export-outlined class="align-sub text-icon" />
        </template>
        <span class="ml-8px">自定义固定按钮</span>
      </AButton>
      <TableColumnSetting v-if="columnsState && columnsState.length > 0" v-model:columns="columnsState" />
    </ASpace>
  </div>
</template>

<style lang="scss" scoped></style>
